<?php
namespace app\admin\model;
use help\IpHelp;
use think\Model;
use base\map\Maps;
use think\facade\Cookie;

class SystemLog extends Model {
	
	protected $name = 'system_log';  			//表名
	protected $pk = 'log_id';  			//主键		
	protected $autoinc  = true;	   	    //主键是否自动增长类型
   	
   	//添加日志
	public static function record($res){
	    $request = request();
        $referer = $request->server('HTTP_REFERER');
        $userInfo = $request->userInfo ?: [];
        
        //判断是否需要加入
        if( strstr(strtolower( getActiveUrl() ),"/msg/")  ){
            return true;
        }
        if( strstr(strtolower( getActiveUrl() ),"install/create")   ){
            return true;
        }
        if( strstr($referer,"/system/logMng/index") ){
            return true;
        }
        
        //收集数据
        $data['uid'] = $userInfo['user_id'] ?? $userInfo['id'] ?? '';
        $data['userinfo'] =   json_encode( $userInfo ,JSON_UNESCAPED_UNICODE);
        $data['client_ip'] = $client_ip = IpHelp::getOnlineIp();
        $data['client_iparea'] = Maps::getIpArea($client_ip);
        $data['api'] = strtolower( getActiveUrl() );
        $data['referer'] = $referer;
        $data['token'] =  $request->header('x-admin-token') ?: Cookie::get('x-admin-token') ?: $request->header('x-token');
        $data['cookie'] = json_encode(Cookie::get(),JSON_UNESCAPED_UNICODE);
        $data['param'] = json_encode( $request->param() ,JSON_UNESCAPED_UNICODE);
        $data['status'] = $res["code"] == 0  ?  1 :  0;
        $data['result'] = $res["code"] == 0 ? '{"code":0,"data":"","msg":"操作成功"}' : json_encode( $res ,JSON_UNESCAPED_UNICODE);
        $data['create_time'] = date('Y-m-d H:i:s');
        
        //保存记录 - 先删后插
        self::whereTime('create_time', '<', '-7 days')->delete();
        self::strict(false)->insert($data);
    }
	
}